package com.ruoyi.framework.web.service;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.system.domain.SysPost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        SysUser user = userService.selectUserByUserName(username);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        // 检查用户岗位
        if (!checkUserPost(user) && !user.getUserName().equals("admin"))
        {
            log.info("登录用户：{} 岗位不符合要求.", username);
            throw new ServiceException(MessageUtils.message("user.post.not.match"));
        }

        passwordService.validate(user);

        return createLoginUser(user);
    }

    /**
     * 检查用户岗位是否符合要求
     * 
     * @param user 用户信息
     * @return 是否符合要求
     */
    private boolean checkUserPost(SysUser user)
    {
        // 获取用户岗位列表
        List<SysPost> posts = userService.selectUserPosts(user.getUserId());
        if (posts == null || posts.isEmpty())
        {
            return false;
        }
        if(CollectionUtil.isEmpty(posts)){
            return true;
        }

        // 使用filter过滤掉postCode为null的岗位
        Map<String, List<SysPost>> collect = posts.stream()
            .filter(post -> post.getPostCode() != null)
            .collect(Collectors.groupingBy(SysPost::getPostCode));

        // 这里可以根据实际需求添加岗位检查逻辑
        // 例如：检查是否包含特定岗位，或者排除某些岗位
        for (SysPost post : posts)
        {
            // 示例：如果岗位编码为"admin"或"manager"则允许登录
            if ("admin".equals(post.getPostCode()) || "manager".equals(post.getPostCode()))
            {
                return true;
            }
            if ("no_log".equals(post.getPostCode())){
                if (!collect.containsKey("manager")){
                    return false;
                }
            }
        }
        
        return false;
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }
}
